package config

import (
	"errors"
	"flow-calc/common"
	"flow-calc/core/log"
)

/**
 *    Description: 函数相关的配置
 *    Date: 2024/3/15
 */

/* 文件配置:
kisType: func
fName: 测试KisFunction_S1
fMode: Save
source:
	name: 被校验的测试数据源1-用户订单维度
	must:
		- userid
		- orderid

option:
	cname: 测试KisConnector_1
	retry_times: 3
	retry_duration: 500
	default_params:
		default1: default1_param
		default2: default2_param
*/

type (
	Source struct {
		Name string   `yaml:"name"`
		Must []string `yaml:"must"`
	}
	Option struct {
		CName         string `yaml:"cname"`
		RetryTimes    int    `yaml:"retry_times"`
		RetryDuration int    `yaml:"retry_duration"`
		DefaultParams FParam `yaml:"default_params"`
	}
	FParam map[string]string
)

type FuncConfig struct {
	KisType  string `yaml:"kisType"`
	FName    string `yaml:"fName"`
	FMode    string `yaml:"fMode"`
	Source   Source `yaml:"source"`
	Option   Option `yaml:"option"`
	connConf *ConnectorConfig
}

func NewFunctionConfig(funcName string, mode common.FunMode, source *Source, option *Option) *FuncConfig {
	config := new(FuncConfig)
	config.KisType = common.FuncType
	config.FName = funcName
	if source == nil {
		log.Logger().Error("fName =%s, 配置文件source 为空！", funcName)
		return nil
	}
	config.Source = *source
	config.FMode = string(mode)
	// 函数类型为Save,Load时候必填kisConnector参数,需要和Connector进行建立流式关系。
	if mode == common.S || mode == common.L {
		if option == nil || option.CName == "" {
			log.Logger().Error("fName =%s, 配置文件option为空或者cname为空!", funcName)
			return nil
		}
	}
	if option != nil {
		config.Option = *option
	}
	return config
}

// AddConnectorConfig 关联connector配置,实现function和Connector进行互相关联
func (fConf *FuncConfig) AddConnectorConfig(cConf *ConnectorConfig) error {
	if cConf == nil {
		return errors.New("ConnectorConfig is nil")
	}
	// function 和 conn 进行关联
	fConf.connConf = cConf
	// connector 和 function 进行关联
	_ = cConf.WithFunc(fConf)
	return nil
}

// GetConnConfig 获取相关的Connector配置
func (fConf *FuncConfig) GetConnConfig() (*ConnectorConfig, error) {
	if fConf.connConf == nil {
		return nil, errors.New("ConnectorConfig is nil")
	} else {
		return fConf.connConf, nil
	}
}
